<template>
	<div>
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i> 用户列表
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-select v-model="query.sex" placeholder="性别" class="handle-select mr10">
					<el-option key="1" label="男" value="0"></el-option>
					<el-option key="2" label="女" value="1"></el-option>
				</el-select>
				<el-input v-model="query.username" placeholder="用户名" class="handle-input mr10"></el-input>
				<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" icon="el-icon-like" @click="handleAddDialog">添加用户</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="uid" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="username" label="用户名"></el-table-column>
				<el-table-column prop="mobile" label="电话号码"></el-table-column>
				<el-table-column prop="email" label="邮箱"></el-table-column>
				<el-table-column label="状态" align="center">
					<template #default="scope">
						<el-tag :type="
				                scope.row.status ==1
				                    ? 'success'
				                    : 'danger'
				            " @click="changeStatus(scope.row)">{{ scope.row.status==1?'正常':'锁定' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="性别" align="center">
					<template #default="scope">
						<el-tag :type="
				                scope.row.sex ==0
				                    ? 'success'
				                    : 'danger'
				            ">{{ scope.row.sex==0?'男':'女' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="头像(查看大图)" align="center">
					<template #default="scope">
						<el-image class="table-td-thumb" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="newtime" label="创建时间"></el-table-column>
				<el-table-column label="操作" width="260" align="center">
					<template #default="scope">
						<el-button type="success" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑
						</el-button>
						<el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, prev, pager, next" :current-page="query.pagenum"
					:page-size="query.pagesize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
			</div>
		</div>

		<!-- 编辑弹出框 -->
		<el-dialog :title="title" v-model="editVisible" width="40%">
			<el-form label-width="100px" :rules="userRules" ref="userRuleRef" :model='userForm'>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="userForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="userForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="userForm.email"></el-input>
				</el-form-item>
				<el-form-item label="电话号码" prop="mobile">
					<el-input v-model="userForm.mobile"></el-input>
				</el-form-item>

			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="saveEdit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import {
		ref,
		reactive
	} from "vue";
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		dbUserLists,
		dbChangeStatus,
		dbAdduser,
		dbDeluser,
		dbEdituser,
		dbSearchuser
	} from "../../api/user";



	export default {
		name: "usertable",
		setup() {
			const query = reactive({
				sex: '',
				username: "",
				pagenum: 1,
				pagesize: 7
			});
			const tableData = ref([]);
			const pageTotal = ref(0);
			// 获取表格数据
			const getData = async () => {
				const {
					status,
					data,
					msg
				} = await dbUserLists(query)
				console.log('数据::', data)
				if (status == 200) {
					/*
					 可更改的 ref 对象，此对象只有一个指向其内部值的属性.value
					*/
					tableData.value = data.lists
					pageTotal.value = parseInt(data.total)

				} else {
					ElMessage.error("数据加载失败!");
				}
			};
			getData();
			//改变用户状态
			const changeStatus = async (userinfo) => {
				let param = {
					uid: userinfo.uid,
					status: userinfo.status == 1 ? 0 : 1
				}
				console.log('参数::', param)
				const {
					status,
					msg,
					data
				} = await dbChangeStatus(param)
				if (status == 200) {
					ElMessage.success("更改成功!");
					//再次调用列表方法
					getData()
				} else {
					ElMessage.error("更改失败!");
				}
			}
			//-----------添加/编辑用户校验规则------
			//自定义校验规则
			var checkEmail = (rule, value, callback) => {
				console.log("........email...")
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (!regEmail.test(value)) {
					//合法邮箱
					return callback(new Error('请输入合法邮箱!'))
				}
				//****
				callback();
			};
			var checkMobile = (rule, value, callback) => {
				console.log("........mobile...")
				const regMobile = /^1[3-9]\d{9}$/
				if (!regMobile.test(value)) {
					//合法邮箱
					return callback(new Error('请输入合法手机号码!'))
				}
				//****
				callback();
			};
			const userRules = {
				username: [{
					required: true,
					message: "请输入用户名!",
					trigger: "blur",
				}],
				password: [{
					required: true,
					message: "请输入密码!",
					trigger: "blur"
				}],
				email: [{
					required: true,
					message: "请输入邮箱!",
					trigger: "blur",
				}, {
					validator: checkEmail,
					trigger: 'blur'
				}],
				mobile: [{
					required: true,
					message: "请输入电话号码!",
					trigger: "blur",
				}, {
					validator: checkMobile,
					trigger: 'blur'
				}],
			};

			const userRuleRef = ref(null);
			//添加用户
			let title = ref('')
			const handleAddDialog = () => {
				title.value = '添加用户'
				//显示添加弹框
				editVisible.value = true;
				//清空信息
				userRuleRef.value.resetFields();
			}
			// 查询操作
			const handleSearch = async () => {
				//获取参数sex/username
				console.log('参数::', query)
				//简单数据校验
				if (query.sex == '' && query.username == '') {
					ElMessage.error("任选其一条件!");
					return false
				}
				const {
					status,
					msg,
					data
				} = await dbSearchuser({
					sex: query.sex,
					keyword: query.username
				})
				if (status == 200) {
					ElMessage.success("查询成功!");
					//分页
					tableData.value = data.lists
					pageTotal.value = parseInt(data.total)

				} else {
					tableData.value = []
					pageTotal.value = 0
					ElMessage.error(`${msg}`);
				}
			};
			// 分页导航
			const handlePageChange = (val) => {
				query.pagenum = val;
				getData();
			};

			// 删除操作
			const handleDelete = (index, userinfo) => {
				// 二次确认删除
				ElMessageBox.confirm("确定要删除吗？", "提示", {
					type: "warning",
				}).then(async () => {
					console.log('信5息::', userinfo)
					const {
						status,
						msg,
						data
					} = await dbDeluser({
						uid: userinfo.uid
					})
					if (status == 200) {
						ElMessage.success("删除成功!");
						//再次调用列表方法
						getData()
					} else {
						ElMessage.error("删除失败!");
					}
				}).catch(() => {});
			};

			// 表格编辑时弹窗和保存
			const editVisible = ref(false);
			let userForm = reactive({
				uid: 0,
				username: "",
				password: "",
				email: '',
				mobile: ''
			});
			let idx = -1;
			const handleEdit = (index, row) => {
				title.value = '编辑用户'
				//赋值
				userForm.uid = row.uid
				idx = index;
				Object.keys(userForm).forEach((item) => {
					userForm[item] = row[item];
				});
				editVisible.value = true;
			};
			const saveEdit = () => {
				console.log('add...user...', userRuleRef)
				userRuleRef.value.validate(async valid => {
					if (valid) {
						//判断是编辑还是添加
						if (userForm.uid) {
							//有uid-编辑
							console.log('UserForm::', userForm)
							const {
								status,
								msg,
								data
							} = await dbEdituser(userForm)
							if (status == 200) {
								ElMessage.success("编辑成功!");
								//隐藏弹框
								editVisible.value = false
								//再次调用列表方法
								getData()
							} else {
								ElMessage.error("编辑失败!");
							}
						} else {
							console.log('UserForm::', userForm)
							const {
								status,
								msg,
								data
							} = await dbAdduser(userForm)
							if (status == 200) {
								ElMessage.success("添加成功!");
								//再次调用列表方法
								getData()
							} else {
								ElMessage.error("添加失败!");
							}
						}
					} else {
						return false;
					}
				});
			};

			return {
				query,
				tableData,
				pageTotal,
				editVisible,
				userForm,
				handleSearch,
				handlePageChange,
				handleDelete,
				handleEdit,
				saveEdit,
				//导出改变状态方法
				changeStatus,
				//导出添加弹出框
				handleAddDialog,
				title,
				//导出规则
				userRules,
				userRuleRef
			};
		},
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		display: inline-block;
	}

	.table {
		width: 100%;
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.table-td-thumb {
		display: block;
		margin: auto;
		width: 40px;
		height: 40px;
	}
</style>
